package com.xmy.cultivate.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmy.cultivate.entity.Quarter;
import com.xmy.cultivate.entity.SchoolNeeds;
import com.xmy.cultivate.entity.TranscriptSet;
import com.xmy.cultivate.entity.TranscriptWritePushSet;
import com.xmy.cultivate.service.IQuarterService;
import com.xmy.cultivate.service.ITranscriptSetService;
import com.xmy.cultivate.service.ITranscriptWritePushSetService;
import com.xmy.cultivate.service.QuartzService;
import com.xmy.cultivate.util.Code;
import com.xmy.cultivate.util.PageResult;
import com.xmy.cultivate.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author hpiggy
 * @since 2024-12-14
 */

@RestController
@RequestMapping("/api/transcriptWritePushSet")
@Scope("prototype")
public class TranscriptWritePushSetController extends BaseController{
    @Autowired
    ITranscriptWritePushSetService iTranscriptWritePushSetService;
    @Autowired
    @Lazy
    ITranscriptSetService iTranscriptSetService;

    @Autowired
    @Lazy
    IQuarterService iQuarterService;

    @Autowired
    @Lazy
    QuartzService quartzService;

    @GetMapping("/getTranscriptWritePushSetList")
    public Result getTranscriptWritePushSetList (
            @RequestParam(value = "pageNum", defaultValue = "-1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(value = "yearPart", required = false) String yearPart,
            @RequestParam(value = "quarterNum", required = false) String quarterNum){

        IPage<TranscriptWritePushSet> iPage = new Page<>(pageNum, pageSize);
        QueryWrapper<TranscriptWritePushSet>  queryWrapper= new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(yearPart), "year_part", yearPart);
        queryWrapper.eq(StringUtils.isNotBlank(quarterNum), "quarter_num", quarterNum);
        queryWrapper.orderByDesc("created_at");
        iTranscriptWritePushSetService.page(iPage, queryWrapper);
        List list = new ArrayList<>();
        LocalDateTime now = LocalDateTime.now();
        //当前年月日
        LocalDate currentDate = now.toLocalDate();
        // 获取当前时间并格式化时分
        String format = now.format(DateTimeFormatter.ofPattern("HH:mm"));

        for (TranscriptWritePushSet transcriptWritePushSet : iPage.getRecords()){
            HashMap hashMap = new HashMap<>();
            hashMap.put("id",transcriptWritePushSet.getId());
            hashMap.put("yearPart",transcriptWritePushSet.getYearPart());
            hashMap.put("quarterNum",transcriptWritePushSet.getQuarterNum());
            hashMap.put("examName",transcriptWritePushSet.getExamName());
            hashMap.put("subjectsIdStr",transcriptWritePushSet.getSubjectsIdStr());
            hashMap.put("yearClassIdStr",transcriptWritePushSet.getYearClassIdStr());
            hashMap.put("pushType",transcriptWritePushSet.getPushType());
            hashMap.put("startDate",transcriptWritePushSet.getStartDate());
            hashMap.put("endDate",transcriptWritePushSet.getEndDate());
            hashMap.put("pushTimes",transcriptWritePushSet.getPushTimes());
            hashMap.put("status",transcriptWritePushSet.getStatus());
            hashMap.put("createdAt",transcriptWritePushSet.getCreatedAt());

            if (transcriptWritePushSet.getPushType() == 1) {
                hashMap.put("isPushStatus", "已推送");
            } else if (transcriptWritePushSet.getPushType() == 2) {
                if (transcriptWritePushSet.getStatus() == 0) {
                    hashMap.put("isPushStatus", "已暂停");
                } else {
                    // 去掉逗号获取第一个
                    String[] split = transcriptWritePushSet.getPushTimes().split(",");
                    if (split.length > 0) {
                        String pushTime = split[0];
                        LocalTime currentLocalTime = LocalTime.parse(format, DateTimeFormatter.ofPattern("HH:mm"));
                        LocalTime pushLocalTime = LocalTime.parse(pushTime, DateTimeFormatter.ofPattern("HH:mm"));

                        if (!currentDate.isBefore(transcriptWritePushSet.getStartDate())) {
                            // 当前日期大于等于开始日期
                            if (!currentLocalTime.isBefore(pushLocalTime)) {
                                hashMap.put("isPushStatus", "已推送");
                            } else {
                                hashMap.put("isPushStatus", "未推送");
                            }
                        } else {
                            hashMap.put("isPushStatus", "未推送");
                        }
                    } else {
                        hashMap.put("isPushStatus", "未推送");
                    }
                }
            }
            /*if (transcriptWritePushSet.getPushType() == 1) {
                hashMap.put("isPushStatus", "已推送");
            }
            if (transcriptWritePushSet.getPushType() == 2){
                //去掉逗号获取第一个
                String[] split = transcriptWritePushSet.getPushTimes().split(",");
                String pushTime = split[0];
                LocalTime currentLocalTime = LocalTime.parse(format, DateTimeFormatter.ofPattern("HH:mm"));
                LocalTime pushLocalTime = LocalTime.parse(pushTime, DateTimeFormatter.ofPattern("HH:mm"));
                if (transcriptWritePushSet.getStatus() == 0) {
                    hashMap.put("isPushStatus", "已暂停");

                }
                if (!currentDate.isBefore(transcriptWritePushSet.getStartDate())) {
                    // 当前日期大于等于开始日期
                    if (!currentLocalTime.isBefore(pushLocalTime)) {
                        // 当前时间大于等于推送时间
                        hashMap.put("isPushStatus", "已推送");
                    } else {
                        hashMap.put("isPushStatus", "未推送");
                    }
                } else {
                    hashMap.put("isPushStatus", "未推送");
                }
            }*/
            list.add(hashMap);
        }
        return new Result(Code.OK, new PageResult<>(list, iPage.getTotal(), iPage.getPages()), "获取列表成功");

    }

    @PostMapping()
    public Result saveTranscriptWritePushSet(@RequestBody TranscriptWritePushSet transcriptWritePushSet) throws Exception {
        String isStatistics = "0";//1已填写，0未填写
        String yearClassIdStr = transcriptWritePushSet.getYearClassIdStr();
        String subjectsIdStr = transcriptWritePushSet.getSubjectsIdStr();
        List<Integer> yearClassIdList = new ArrayList<>();
        List<Integer> subjectsIdList = new ArrayList<>();
        if (yearClassIdStr != null){
            String[] yearClassIds = yearClassIdStr.split(",");
            for (String s : yearClassIds) {
                yearClassIdList.add(Integer.valueOf(s));
            }
        }
        if (subjectsIdStr != null){
            String[] subjectsIds = subjectsIdStr.split(",");
            for (String s : subjectsIds) {
                subjectsIdList.add(Integer.valueOf(s));
            }
        }
        // 获取当前日期时间
        LocalDateTime now = LocalDateTime.now();
        LocalDate currentDate = now.toLocalDate();

        // 获取当前时间并格式化
        String pushTimes = now.format(DateTimeFormatter.ofPattern("HH:mm"));
        if (transcriptWritePushSet.getPushType() == 1){
            transcriptWritePushSet.setStartDate(currentDate);
            transcriptWritePushSet.setPushTimes(pushTimes);
        }
        iTranscriptWritePushSetService.save(transcriptWritePushSet);
        Quarter quarter = iQuarterService.getQuarterForYearAndNum(transcriptWritePushSet.getYearPart(), transcriptWritePushSet.getQuarterNum());
        Integer yearPart = quarter.getYearPart();
        Integer quarterNum = quarter.getNum();

        //单次推送
        if(transcriptWritePushSet.getPushType() == 1) {
            Integer examNum = transcriptWritePushSet.getExamNum();
            Long writePushSetid = transcriptWritePushSet.getId();
            //推送
            iTranscriptWritePushSetService.scorePush( writePushSetid,yearPart, quarterNum, examNum, isStatistics, quarter, yearClassIdList,subjectsIdList);
            return new Result(Code.OK, "", "推送成功");
        }else if(transcriptWritePushSet.getPushType() == 2){
            //定时推送
            LocalDate startDate = transcriptWritePushSet.getStartDate();
            LocalDate endDate = transcriptWritePushSet.getEndDate();
            String id = String.valueOf(transcriptWritePushSet.getId());
            String[] split = transcriptWritePushSet.getPushTimes().split(",");
            for (String pushTime : split) {
                //生成定时推送
                quartzService.setSchedulDailyJob( id,startDate, endDate, pushTime);
            }
        }
        return new Result(Code.OK, "", "添加成功");
    }


    @PutMapping("/updateTranscriptWritePushSet")
    public Result updateTranscriptWritePushSet(@RequestBody TranscriptWritePushSet transcriptWritePushSet) {
        TranscriptWritePushSet transcriptWritePushSet1 = iTranscriptWritePushSetService.getById(transcriptWritePushSet.getId());
        if (transcriptWritePushSet1 == null) {
            return new Result(Code.EXP_ERROR, null, "该数据不存在");
        }
        boolean update = iTranscriptWritePushSetService.updateById(transcriptWritePushSet);
        if (!update) {
            return new Result(Code.ERROR, null, "暂停失败");
        }
        return new Result(Code.OK, "", "暂停成功");
    }
}
